package com.stephen.mycc.launcher.base;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.NinePatchDrawable;
import android.graphics.drawable.StateListDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.stephen.mycc.launcher.R;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StephenToolUtils {
    public static final String ResTypeDrawable = "drawable",ResTypeString = "string";
    public static boolean StephenLogSwitch = true;
    private static StephenAlertDialog alterDialog = null;
    private static StephenCustomDialog loadingDialog = null;
    public static String MasterColorHex = "#FF8C00",MasterFontColorHex = "#ffffff";
    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);

    //判断处理log过长问题(Android系统的单条日志打印长度最长:4*1024)
    private static void outputLogCompatibleMaxLength(String logStr,boolean isError){
        int maxLength = 3000;
        if(logStr.length() > maxLength){
            for(int i=0,j=1;i < logStr.length();i+=maxLength,j++){
                if(isError){
                    if(i+maxLength < logStr.length()) {
                        Log.e("StephenLog","日志过长分段"+j+"==>"+logStr.substring(i, i + maxLength));
                    }else {
                        Log.e("StephenLog","日志过长分段"+j+"==>"+logStr.substring(i, logStr.length()));
                    }
                }else{
                    if(i+maxLength < logStr.length()) {
                        System.out.println("日志过长分段"+j+"==>"+logStr.substring(i, i + maxLength));
                    }else {
                        System.out.println("日志过长分段"+j+"==>"+logStr.substring(i, logStr.length()));
                    }
                }
            }//end of for
        }else{
            if(isError){
                Log.e("StephenLog",logStr);
            }else{
                System.out.println("=====>"+logStr);
            }
        }
    }

    public static void LogD(String logMsg){
        if(StephenLogSwitch)outputLogCompatibleMaxLength(logMsg,false);
    }

    public static void LogE(String logMsg){
        if(StephenLogSwitch)outputLogCompatibleMaxLength(logMsg,true);
    }

    public static void showLongHintInfo(Context context,String text){
        Toast.makeText(context, text, Toast.LENGTH_LONG).show();
    }

    public static void showShortHintInfo(Context context,String text){
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    public static void showHintInfoDialog(Context context,String message){
        showAlertInfoDialog(context,"提示",message,false,true,"知道了",null);
    }
    public static void showHintInfoDialog(Context context,String message,StephenAlertDialog.OnStephenClickListener centerListener){
        showAlertInfoDialog(context,"提示",message,false,true,"知道了",centerListener);
    }
    public static void showHintInfoDialog(Context context,String title,String message,StephenAlertDialog.OnStephenClickListener leftListener){
        showAlertInfoDialog(context,title,message,false,true,"确定","取消",leftListener,null);
    }
    public static void showAlertInfoDialog(Context context,String title,String message,boolean outsideCancel,boolean backCancel,String centerStr,StephenAlertDialog.OnStephenClickListener centerListener){
        showAlertInfoDialog(context, title, message, outsideCancel, backCancel, null, centerStr, null, null, centerListener, null);
    }
    public static void showAlertInfoDialog(Context context,String title,String message,boolean outsideCancel,boolean backCancel,String leftStr,String rightStr,StephenAlertDialog.OnStephenClickListener leftListener,StephenAlertDialog.OnStephenClickListener rightListener){
        showAlertInfoDialog(context, title, message, outsideCancel, backCancel, leftStr, null, rightStr, leftListener, null, rightListener);
    }
    public static void showAlertInfoDialog(Context context,String title,String message,boolean outsideCancel,boolean backCancel,String leftStr,String centerStr,String rightStr,
                                           StephenAlertDialog.OnStephenClickListener leftListener,StephenAlertDialog.OnStephenClickListener centerListener, StephenAlertDialog.OnStephenClickListener rightListener){
        try {
            StephenAlertDialog.Builder builder = new StephenAlertDialog.Builder(context);
            builder.setTitle(title);
            builder.setMessage(message);
            builder.setBackCancel(backCancel);
            builder.setCurStyle(StephenAlertDialog.StyleAndroid);
            if(!TextUtils.isEmpty(leftStr))builder.setPositiveButton(leftStr,leftListener);
            if(!TextUtils.isEmpty(centerStr))builder.setNeutralButton(centerStr,centerListener);
            if(!TextUtils.isEmpty(rightStr))builder.setNegativeButton(rightStr,rightListener);
            alterDialog = builder.create();
            alterDialog.show();
            alterDialog.setCanceledOnTouchOutside(outsideCancel);//show之前设置无效
        } catch (Exception e) {//避免context先销毁再弹框时报错
            e.printStackTrace();
        }
    }
    //关闭AlertInfo对话框
    public static void closeAlertInfoDialog(){
        try {
            if(null != alterDialog)alterDialog.dismiss();
            alterDialog = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //显示loading对话框
    public static void showLoadingDialog(Context context,String showStr){
        try {
            if(null != loadingDialog)return;
            RelativeLayout loadingRy = new RelativeLayout(context);

            GradientDrawable loadingRyBgShape = new GradientDrawable();
            loadingRyBgShape.setColor(Color.parseColor("#e1666666"));
            loadingRyBgShape.setCornerRadius(StephenToolUtils.dip2px(context,6));
            StephenToolUtils.setBackgroundAllVersion(loadingRy,loadingRyBgShape);

            ProgressBar loadingPB = new ProgressBar(context);
            loadingPB.setIndeterminateDrawable(context.getResources().getDrawable(R.drawable.progressbar_style_drawable2_shape));
            RelativeLayout.LayoutParams loadingPbLp = new RelativeLayout.LayoutParams(StephenToolUtils.dip2px(context,60),StephenToolUtils.dip2px(context,60));
            loadingPbLp.addRule(RelativeLayout.CENTER_IN_PARENT);
            loadingRy.addView(loadingPB,loadingPbLp);

            TextView loadingT = new TextView(context);
            loadingT.setGravity(Gravity.CENTER);
            loadingT.setTextColor(Color.parseColor("#000000"));
            loadingT.setTextSize(15);
            loadingT.setText(showStr);
            //loadingT.setVisibility(View.GONE);
            RelativeLayout.LayoutParams loadingTLp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            loadingTLp.setMargins(StephenToolUtils.dip2px(context,5),StephenToolUtils.dip2px(context,5),StephenToolUtils.dip2px(context,5),StephenToolUtils.dip2px(context,15));
            loadingTLp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            loadingTLp.addRule(RelativeLayout.CENTER_HORIZONTAL);
            loadingRy.addView(loadingT,loadingTLp);

            loadingDialog = new StephenCustomDialog(context,loadingRy, R.style.loadingDialogTheme);
            loadingDialog.setCustomDialogWidthHeightWithDp(160,140);
            loadingDialog.show();//显示Dialog
        } catch (Exception e) {//避免context先销毁再弹框时报错
            e.printStackTrace();
        }
    }
    //关闭loading对话框
    public static void closeLoadingDialog(){
        try {
            if(null != loadingDialog)loadingDialog.dismiss();
            loadingDialog = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //启动activity并关闭
    public static void startActivityAndFinish(Activity activity,Class<?> cls){
        startActivityAndFinish(activity, cls, null);
    }
    public static void startActivityAndFinish(Activity activity,Class<?> cls,Bundle bundle){
        startActivityAndFinish(activity, cls, bundle, -1, -1);
    }
    public static void startActivityAndFinish(Activity activity,Class<?> cls,Bundle bundle,int enterAnim, int exitAnim){
        if(null == activity || null ==cls)return;
        Intent intent = new Intent(activity,cls);
        if (null != bundle)intent.putExtras(bundle);
        activity.startActivity(intent);
        activity.finish();
        if(-1 == enterAnim && -1 == exitAnim){
            activity.overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
        }else{
            activity.overridePendingTransition(enterAnim,exitAnim);
        }
    }
    //启动activity并关闭且清除顶层
    public static void startActivityAndClearTopFinish(Context context,Class<?> cls,Bundle bundle){
        if(null == context || null ==cls)return;
        Intent intent = new Intent(context,cls);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
        if(null != bundle)intent.putExtras(bundle);
        context.startActivity(intent);
    }
    public static void startActivityAndClearTopFinish(Activity activity,Class<?> cls,Bundle bundle){
        if(null == activity || null ==cls)return;
        Intent intent = new Intent(activity,cls);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
        if(null != bundle)intent.putExtras(bundle);
        activity.startActivity(intent);
        activity.finish();
        activity.overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
    }
    //启动activity不关闭
    public static void startActivityNoFinish(Activity activity,Class<?> cls){
        startActivityNoFinish(activity, cls, null);
    }
    public static void startActivityNoFinish(Activity activity,Class<?> cls,Bundle bundle){
        startActivityNoFinish(activity, cls, bundle, 520);
    }
    public static void startActivityNoFinish(Activity activity,Class<?> cls,Bundle bundle,int requestCode){
        startActivityNoFinish(activity, cls, bundle, requestCode, -1, -1);
    }
    public static void startActivityNoFinish(Activity activity,Class<?> cls,Bundle bundle,int requestCode,int enterAnim, int exitAnim){
        if(null == activity || null ==cls)return;
        Intent intent = new Intent(activity,cls);
        if(null != bundle)intent.putExtras(bundle);
        activity.startActivityForResult(intent,requestCode);//requestCode不能为0和负数,不然onActivityResult不执行
        if(-1 == enterAnim && -1 == exitAnim){
            activity.overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
        }else{
            activity.overridePendingTransition(enterAnim,exitAnim);
        }
    }

    public static boolean isViewFileOrDirExists(String path) {
        File pathFile = new File(path);
        if(null != pathFile){
            return pathFile.exists();
        }else{
            return false;
        }
    }

    public static void ViewOrCreateDir(String dirPath) {
        File dir = new File(dirPath);
        if(!dir.exists())dir.mkdirs();
    }

    public static void ViewOrCreateFile(String filePath) {
        try {
            File dir = new File(filePath);
            ViewOrCreateDir(dir.getParentFile().getAbsolutePath());
            if(!dir.exists())dir.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static boolean ViewAndDeleteDirOrFile(String filePath) {
        if(!TextUtils.isEmpty(filePath)) {
            File dir = new File(filePath);
            if(dir.exists())return dir.delete();
        }//end of if
        return false;
    }

    public static boolean isHaveSDCard(){
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public static String getSD_CardRootPath(){
        if(isHaveSDCard())return Environment.getExternalStorageDirectory().getAbsolutePath();
        return null;
    }

    public static Bitmap rotateBitmap(Bitmap bitmap, int angle) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return Bitmap.createBitmap(bitmap, 0, 0,bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }//end of if
        return inSampleSize;
    }

    public static Bitmap scaleBitmap(byte[] data, int newWidth, int newHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(data,0,data.length,options);
        options.inSampleSize = calculateInSampleSize(options, newWidth, newHeight);
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length,options);
        return bitmap;
    }

    public static Bitmap scaleBitmap(Bitmap org, int newWidth, int newHeight) {
        if(null == org)return null;
        Matrix matrix = new Matrix();
        matrix.postScale((float) newWidth / org.getWidth(), (float) newHeight / org.getHeight());
        return Bitmap.createBitmap(org, 0, 0, org.getWidth(), org.getHeight(), matrix, true);
    }

    //bitmap转为base64
    public static String bitmapToBase64String(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (null != bitmap) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                baos.flush();
                baos.close();
                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }//end of if
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != baos) {
                    baos.flush();
                    baos.close();
                }//end of if
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static Drawable bitmapToDrawable(Bitmap bitmap) {
        return bitmap == null ? null : new BitmapDrawable(bitmap);
    }

    //以最省内存的方式读取本地资源的图片
    public static Bitmap getBitmapFromResId(Context context, int resId){
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.ARGB_4444;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    //以最省内存的方式读取本地资源的图片
    public static Bitmap getBitmapForSDCard(String imagePath){
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.ARGB_4444;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        return BitmapFactory.decodeFile(imagePath, opt);
    }

    public static boolean copyAssetFiles(Context context,String assetFolderName,File outDir){
        try{
            AssetManager assetManager = context.getAssets();
            String[] fileAry = assetManager.list(assetFolderName);
            if(null != fileAry && fileAry.length > 0)for(String file : fileAry)copyAssetFile(context,assetFolderName,file,outDir);
            return true;
        }catch(IOException e){
            e.printStackTrace();
            return false;
        }
    }

    public static File copyAssetFile(Context context,String assetFilePath,String assetFileName,File outDir){
        try{
            File outFile = new File(outDir,assetFileName);
            if(!outFile.exists()){
                if(!outDir.exists())outDir.mkdirs();
                InputStream is;
                AssetManager assetManager = context.getAssets();
                if(TextUtils.isEmpty(assetFilePath)){
                    is = assetManager.open(assetFileName);
                }else{
                    is = assetManager.open(assetFilePath+File.separator+assetFileName);
                }
                FileOutputStream out = new FileOutputStream(outFile);
                byte buf[] = new byte[1024];
                int len;
                while((len = is.read(buf)) > 0)out.write(buf, 0, len);
                out.close();
                is.close();
            }//end of if
            return outFile;
        }catch(IOException e){
            e.printStackTrace();
            return null;
        }
    }

    public static String readRawFileContentToStr(Context context,int rawId){
        try {
            InputStream is = context.getResources().openRawResource(rawId);
            if(null != is){
                byte[] buffer = new byte[is.available()];
                is.read(buffer);
                return new String(buffer,"UTF-8");
            }else{
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //btn selector
    public static StateListDrawable createSelector(String stateNormal,String statePressed, String stateFocused, String stateDisabled) {
        Drawable normal = stateNormal == null ? null : BitmapDrawable.createFromPath(stateNormal);
        Drawable pressed = statePressed == null ? null : BitmapDrawable.createFromPath(statePressed);
        Drawable focused = stateFocused == null ? null : BitmapDrawable.createFromPath(stateFocused);
        Drawable disabled = stateDisabled == null ? null : BitmapDrawable.createFromPath(stateDisabled);
        return createSelector(normal,pressed,focused,disabled);
    }

    //btn selector
    public static StateListDrawable createSelector(Drawable normal,Drawable pressed, Drawable focused, Drawable disabled) {
        StateListDrawable stateListDrawable = new StateListDrawable();
        stateListDrawable.addState(new int[] {android.R.attr.state_pressed,android.R.attr.state_enabled }, pressed);
        stateListDrawable.addState(new int[] {android.R.attr.state_enabled,android.R.attr.state_focused }, focused);
        stateListDrawable.addState(new int[] {android.R.attr.state_focused }, focused);
        stateListDrawable.addState(new int[] {android.R.attr.state_enabled }, normal);
        stateListDrawable.addState(new int[] {android.R.attr.state_window_focused }, disabled);
        stateListDrawable.addState(new int[] {},normal);
        return stateListDrawable;
    }

    //checkbox/radio selector(warning:state_enabled below for state_checked)
    public static StateListDrawable createSelector(Drawable normal,Drawable checked) {
        StateListDrawable stateListDrawable = new StateListDrawable();
        stateListDrawable.addState(new int[] {android.R.attr.state_checked}, checked);
        stateListDrawable.addState(new int[] {android.R.attr.state_enabled}, normal);
        return stateListDrawable;
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static Point getScreenWHToPoint(Activity context){
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return new Point(dm.widthPixels,dm.heightPixels);
    }

    public static boolean isShouldHideKeyboard(View view, MotionEvent event) {
        if(null != view && (view instanceof EditText)){
            int[] location = {0, 0};
            view.getLocationInWindow(location);
            int left = location[0],top = location[1],bottom = top + view.getHeight(),right = left + view.getWidth();
            return !(event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom);
        }//end of if
        return false;
    }

    //从Activity获取rootView根节点
    public static View getActivityRootView(Activity activity){
        return ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0);
    }

    //获取视图中根布局并转换成ViewGroup
    public static ViewGroup convertRootViewToViewGroup(View mainView){
        if(null != mainView.getRootView() && mainView.getRootView() instanceof ViewGroup){
            return (ViewGroup)mainView.getRootView();//ViewGroup subclass AbsoluteLayout, AdapterView, FrameLayout, LinearLayout, RelativeLayout, SlidingDrawer
        }//end of if
        return null;
    }

    //得到子控件在父布局中的索引
    public static int getChildViewInRootViewIndex(ViewGroup rootView,View mainView,int findViewId){
        if(null == rootView)rootView = convertRootViewToViewGroup(mainView);
        if(null != rootView){
            for(int i = 0;i < rootView.getChildCount();i++){
                View childView = rootView.getChildAt(i);
                if(null != childView && findViewId == childView.getId())return i;
            }//end of for
        }//end of if
        return -1;
    }

    //这是设置图片的不同状态,设置TextView环绕图片(direction value is 1/left,2/top,3/right,4/bottom)
    public static void setTextViewAroundDrawable(Context context, TextView textView, int imgResId, int imgWidthDp, int imgHeightDp, int imgPaddingDp, int direction) {
        setTextViewAroundDrawable(context,textView,context.getResources().getDrawable(imgResId),imgWidthDp,imgHeightDp,imgPaddingDp,direction);
    }
    public static void setTextViewAroundDrawable(Context context,TextView textView,Drawable aroundDrawable,int imgWidthDp,int imgHeightDp,int imgPaddingDp,int direction){
        if(null != textView){
            if(null != aroundDrawable)aroundDrawable.setBounds(0,0, dip2px(context,imgWidthDp),dip2px(context,imgHeightDp));
            textView.setCompoundDrawablePadding(dip2px(context,imgPaddingDp));
            switch(direction){
                case Gravity.LEFT:
                    textView.setCompoundDrawables(aroundDrawable, null, null, null);
                    break;
                case Gravity.TOP:
                    textView.setCompoundDrawables(null, aroundDrawable, null, null);
                    break;
                case Gravity.RIGHT:
                    textView.setCompoundDrawables(null, null, aroundDrawable, null);
                    break;
                case Gravity.BOTTOM:
                    textView.setCompoundDrawables(null, null, null, aroundDrawable);
                    break;
            }//end of switch
        }//edn of if
    }

    public static int generateViewId() {
        for(;;){
            final int result = sNextGeneratedId.get();
            int newValue = result + 1;
            if (newValue > 0x00FFFFFF) newValue = 1;//Roll over to 1, not 0.
            if(sNextGeneratedId.compareAndSet(result, newValue))return result;
        }//end of for
    }

    //兼容低版本的设置View背景方法,避免报错
    public static void setBackgroundAllVersion(Context context,View view,int bgResId){
        setBackgroundAllVersion(view,context.getResources().getDrawable(bgResId));
    }

    public static void setBackgroundAllVersion(View view,Bitmap bgBitmap){
        setBackgroundAllVersion(view,bitmapToDrawable(bgBitmap));
    }

    public static void setBackgroundAllVersion(View view,Drawable bgDrawable){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
            view.setBackground(bgDrawable);
        }else{
            view.setBackgroundDrawable(bgDrawable);
        }
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {
        if(drawable instanceof BitmapDrawable){
            return ((BitmapDrawable) drawable).getBitmap();
        }else if(drawable instanceof NinePatchDrawable){
            Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            drawable.draw(canvas);
            return bitmap;
        }else{
            return null;
        }
    }

    //序列化对象
    public static String serializeObject(Object object){
        try {
            if (null != object) {
                long startTime = System.currentTimeMillis();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
                objectOutputStream.writeObject(object);
                String serStr = byteArrayOutputStream.toString("ISO-8859-1");
                serStr = java.net.URLEncoder.encode(serStr, "UTF-8");
                objectOutputStream.close();
                byteArrayOutputStream.close();
                //System.out.println("序列化成功,耗时为:"+ (System.currentTimeMillis() - startTime)+"ms");
                return serStr;
            }else{
                System.out.println("序列对象是null,返回null");
                return null;
            }
        } catch (IOException e) {
            System.out.println("序列化异常!");
            e.printStackTrace();
            return null;
        }
    }
    //反序列化对象
    public static Object deSerializationObject(String saveObjStr){
        try {
            if(!TextUtils.isEmpty(saveObjStr) && saveObjStr.length() > 0){
                long startTime = System.currentTimeMillis();
                String redStr = java.net.URLDecoder.decode(saveObjStr, "UTF-8");
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(redStr.getBytes("ISO-8859-1"));
                ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
                Object obj = objectInputStream.readObject();
                objectInputStream.close();
                byteArrayInputStream.close();
                //System.out.println("反序列化成功,耗时为:" + (System.currentTimeMillis() - startTime)+"ms");
                return obj;
            }else{
                System.out.println("反序列对象是null,返回null");
                return null;
            }
        } catch (Exception e) {
            System.out.println("反序列化异常!");
            e.printStackTrace();
            return null;
        }
    }

    //计算字符串的宽度(像素)
    public static float getStringPixelWidth(Paint strPaint, String str){
        return strPaint.measureText(str);
    }

    //计算字符串的高度(像素)
    public static float getStringPixelHeight(Paint strPaint){
        Paint.FontMetrics fontMetrics = strPaint.getFontMetrics();
        return fontMetrics.bottom - fontMetrics.top;
    }

    //格式化字符串
    public static String formatStr(String format, int args) {
        return String.format(format, args);
    }

    public static Point getScreenSize(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        return new Point(wm.getDefaultDisplay().getWidth(), wm.getDefaultDisplay().getHeight());
    }

    public static void removeViewFromParent(View view) {
        if(view == null)return;
        ViewParent parent = view.getParent();
        if(parent != null)((ViewGroup) parent).removeView(view);
    }

    public static String getDeviceIMEI(Context context){
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if(null != tm)return tm.getDeviceId();
        return null;
    }

    public static void callPhoneNumber(Activity activity,String phone_number){
        if(!TextUtils.isEmpty(phone_number)){
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone_number));
            activity.startActivity(intent);//内部类
        }else{
            showShortHintInfo(activity,"抱歉,不能完成拨号,号码为空!");
        }
    }

    public static void callSmsContentView(Activity activity,String smsBody){
        if(!TextUtils.isEmpty(smsBody)){
            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"));
            intent.putExtra("sms_body", smsBody);
            activity.startActivity(intent);
        }//end of if
    }

    public static void copyTextToSystemClipboard(Activity activity,String text){
        ClipboardManager cm = (ClipboardManager)activity.getSystemService(Context.CLIPBOARD_SERVICE);
        if(null != cm && !TextUtils.isEmpty(text)){
            cm.setText(text);
            showShortHintInfo(activity,"内容已经成功复制,粘贴即可使用!");
        }else{
            showShortHintInfo(activity,"抱歉,复制异常,不能完成复制!");
        }
    }

    //获取当前版本标识号
    public static int getCurrentVersionCode(Context mContext){
        try {
            return mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    //获取当前版本号
    public static String getCurrentVersionName(Context mContext){
        try {
            return mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    //得到进程名字
    public static String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if(null == runningApps)return null;
        for(ActivityManager.RunningAppProcessInfo appInfo : runningApps)if(appInfo.pid == pid)return appInfo.processName;
        return null;
    }

    public static boolean isActivityTopRunning(Context context,String activityName) {//e.g:com.stephen.smart.home.remoter.media.activity.MainRoomTvActivity(class.getCanonicalName())
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasksInfo = mActivityManager.getRunningTasks(1);
        if(null != tasksInfo && tasksInfo.size() > 0 && activityName.equals(tasksInfo.get(0).topActivity.getClassName()))return true;
        return false;
    }

    //判断一个Service是否运行(serviceName是包名+服务的类名,例如:net.loonggg.testbackstage.TestService)
    public static boolean isServiceWorking(Context context, String serviceName) {
        ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for(ActivityManager.RunningServiceInfo service : myManager.getRunningServices(Integer.MAX_VALUE)) {
            if(serviceName.equals(service.service.getClassName().toString()))return true;
        }//end of for
        return false;
    }

    public static boolean isAppRunningForeground (Context context) {
        ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String currentPackageName = cn.getPackageName();
        if(!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(context.getPackageName()))return true;
        return false;
    }

    //重新计算ListView或GridView高度
    public static int reSetAbsListViewHeightBasedOnChildren(AbsListView absListView) {
        int totalHeight = 0;
        ListAdapter listAdapter = absListView.getAdapter();
        if(null == listAdapter)return 0;
        if(absListView instanceof ListView){
            for(int i = 0; i < listAdapter.getCount(); i++){
                View listItem = listAdapter.getView(i, null, absListView);
                listItem.measure(0, 0);//计算子项View的宽高
                totalHeight += listItem.getMeasuredHeight();
            }//end of for
            totalHeight += (((ListView)absListView).getDividerHeight() * (listAdapter.getCount() - 1));
        }else if(absListView instanceof GridView){
            int column = -1;
            try{//getNumColumns一直是-1,mRequestedNumColumns反而有值
                Field field = GridView.class.getDeclaredField("mRequestedNumColumns"); //获得申明的字段
                field.setAccessible(true); //设置访问权限
                column = Integer.valueOf(field.get((absListView)).toString());//获取字段的值
            }catch (Exception e1) {}
            if(-1 != column){
                for(int i = 0; i < listAdapter.getCount(); i += column){
                    View listItem = listAdapter.getView(i, null, absListView);
                    listItem.measure(0, 0);//计算子项View的宽高
                    totalHeight += listItem.getMeasuredHeight();
                }//end of for
            }//end of if
            totalHeight += (((GridView)absListView).getVerticalSpacing() * (listAdapter.getCount() - 1));
        }//end of else if
        ViewGroup.LayoutParams params = absListView.getLayoutParams();
        if(null != params){
            params.height = totalHeight;
            absListView.setLayoutParams(params);
        }//end of if
        return totalHeight;
    }
    //设置GridView的宽高
    public static void reSetGridViewHeightBasedOnChildren(Context context,GridView gridView,int dataSize,int numColumns,int rowHeightDp,int verticalSpacingDp){
        int row = 1;
        if(dataSize > numColumns)row = (int)Math.ceil((double)dataSize/(double)numColumns);
        ViewGroup.LayoutParams params = gridView.getLayoutParams();
        if(null != params){
            params.height = (dip2px(context,rowHeightDp) * row) + ((row-1) * dip2px(context,verticalSpacingDp));
            gridView.setLayoutParams(params);
        }//end of if
    }

    //安装apk方法
    public static void installApk(Context context,String filename) {
        File file = new File(filename);
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    //double保留小数点后两位
    public static String keepTwoDouble(double d){
        DecimalFormat df = new DecimalFormat("0.00");
        String format = df.format(d);
        String.valueOf(format);
        return format;
    }

    public static void setActivityAlpha(Activity activity,float alpha) {
        WindowManager.LayoutParams params = activity.getWindow().getAttributes();
        params.alpha = alpha;
        activity.getWindow().setAttributes(params);
    }

    public static int strInStringArray(String a, String[] b) {
        if(TextUtils.isEmpty(a) || null == b)return -1;
        for(int i = 0; i < b.length; i++)if(a.equals(b[i]))return i;
        return -1;
    }

    public static int strInStringList(String a, List<String> b) {
        if(TextUtils.isEmpty(a) || null == b)return -1;
        for(int i = 0; i < b.size(); i++)if(a.equals(b.get(i)))return i;
        return -1;
    }

    public static long getNumberInString(String string){
        if(TextUtils.isEmpty(string))return Long.MAX_VALUE;
        String retStr = "";
        for(int i=0;i<string.length();i++)if(string.charAt(i) >= 48 && string.charAt(i) <= 57)retStr += string.charAt(i);
        if(TextUtils.isEmpty(retStr))return Long.MAX_VALUE;
        return Long.parseLong(retStr);
    }

    public static void setActivityBackgroundAlpha(Activity activity,float bgAlpha) {
        if(null == activity)return;
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        activity.getWindow().setAttributes(lp);
    }

    public static PointF getScreenWidthHeightPixels(Context context){
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(dm);
        return new PointF(dm.widthPixels,dm.heightPixels);
    }

    public static PointF getScreenWidthHeightPixels(Activity activity){
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return new PointF(dm.widthPixels,dm.heightPixels);
    }

    public static boolean checkCurRunningIsPad(Context context){//smallestScreenWidth >= 600px is pad
        return context.getResources().getConfiguration().smallestScreenWidthDp >= 600;
    }

    public static void setViewLinearLayoutMargins(Context context,View view,int leftMarginDp, int topMarginDp, int rightMarginDp, int bottomMarginDp){
        if(null == context || null == view || null == view.getLayoutParams())return;
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)view.getLayoutParams();
        lp.setMargins(StephenToolUtils.dip2px(context,leftMarginDp),StephenToolUtils.dip2px(context,topMarginDp),StephenToolUtils.dip2px(context,rightMarginDp),StephenToolUtils.dip2px(context,bottomMarginDp));
        view.setLayoutParams(lp);
    }

    public static String readFileContentToString(String fileName) {
        File file = new File(fileName);
        Long fileLength = file.length();
        byte[] fileContent = new byte[fileLength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(fileContent);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            return new String(fileContent, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    //获取资源的Id,resType用顶部定义的类型
    public static int getResourcesIdForName(Context context,String resName,String resType){
        if(null == context || null == context.getResources() || TextUtils.isEmpty(resName) || TextUtils.isEmpty(resType))return -1;
        return context.getResources().getIdentifier(resName, resType, context.getApplicationInfo().packageName);
    }

    //字节数组转16进制字符串
    public static String bytes2HexString(byte[] b) {
        String r = "";
        for(int i = 0; i < b.length; i++){
            String hex = Integer.toHexString(b[i] & 0xFF);
            if(hex.length() == 1)hex = '0' + hex;
            r += hex.toUpperCase();
        }//end of for
        return r;
    }

    //应用重新启动自身）
    public static void restartSelfApplication(Context context) {
        final Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    //判断是否有虚拟按键
    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        try{
            Resources rs = context.getResources();
            int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
            if(id > 0)hasNavigationBar = rs.getBoolean(id);
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if("1".equals(navBarOverride)){
                hasNavigationBar = false;
            }else if("0".equals(navBarOverride)){
                hasNavigationBar = true;
            }
        }catch (Exception e){
            hasNavigationBar = false;
        }
        return hasNavigationBar;
    }

    //隐藏虚拟按键,并且全屏,onCreate设置布局前调用
    public static void setHideVirtualKey(Window window){
        //保持布局状态/布局位于状态栏下方/全屏/隐藏导航栏
        int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE|View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_FULLSCREEN|View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
        if(Build.VERSION.SDK_INT>=19){
            uiOptions |= 0x00001000;
        }else{
            uiOptions |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
        }
        window.getDecorView().setSystemUiVisibility(uiOptions);
    }

    //只隐藏状态栏,onCreate设置布局前调用
    public static void setHideSystemTitleBar(Activity activity){
        activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
        activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    //dialog全屏,show设置布局前调用
    private void setDialogHideSystemFull(final Dialog dialog){
        try {
            if(null == dialog)return;
            dialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
            dialog.getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
                @Override
                public void onSystemUiVisibilityChange(int visibility) {
                    int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |//布局位于状态栏下方
                            View.SYSTEM_UI_FLAG_FULLSCREEN |//全屏
                            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |//隐藏导航栏
                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
                    if (Build.VERSION.SDK_INT >= 19) {
                        uiOptions |= 0x00001000;
                    } else {
                        uiOptions |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
                    }
                    dialog.getWindow().getDecorView().setSystemUiVisibility(uiOptions);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int generateRandomNum(int min,int max) {
        if(min < 0 || max < 0 || max < min)return -1;
        return (new Random()).nextInt(max)%(max-min+1) + min;
    }

    public static void startAplication(Context context,String appPackageName,String appName,boolean isGoMarket){
        try{
            Intent intent = context.getPackageManager().getLaunchIntentForPackage(appPackageName);
            context.startActivity(intent);
        }catch(Exception e){
            if(isGoMarket){
                try{
                    Intent startIntent = new Intent("android.intent.action.MAIN");
                    startIntent.addCategory("android.intent.category.APP_MARKET");
                    startIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(startIntent);
                    showShortHintInfo(context,appName+"没有安装,请下载...");
                }catch(Exception e1){
                    showShortHintInfo(context,"貌似你没有安装一款应用市场,无法跳转应用市场下载"+appName);
                }
            }else{
                showShortHintInfo(context,appName+"打开失败,请先安装...");
            }
        }
    }

    //显示与隐藏状态栏
    public static void fullscreen(Activity activity,boolean enable) {
        if(enable) { //显示状态栏
            WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            activity.getWindow().setAttributes(lp);
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } else { //隐藏状态栏
            WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
            lp.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            activity.getWindow().setAttributes(lp);
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
    }

    public static String delHTMLTag(String htmlStr) {
        // 过滤script标签
        Pattern p_script = Pattern.compile("<script[^>]*?>[\\s\\S]*?<\\/script>", Pattern.CASE_INSENSITIVE);//script的正则表达式
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll("");
        // 过滤style标签
        Pattern p_style = Pattern.compile("<style[^>]*?>[\\s\\S]*?<\\/style>", Pattern.CASE_INSENSITIVE);//style的正则表达式
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll("");
        // 过滤html标签
        Pattern p_html = Pattern.compile("<[^>]+>", Pattern.CASE_INSENSITIVE);//HTML标签的正则表达式
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll("");
        // 过滤空格回车标签
        Pattern p_space = Pattern.compile("\\s*|\t|\r|\n", Pattern.CASE_INSENSITIVE);//空格回车换行符
        Matcher m_space = p_space.matcher(htmlStr);
        htmlStr = m_space.replaceAll("");
        return htmlStr.trim(); // 返回文本字符串
    }
}
